package controller

import (
	"fmt"
	"math"
	"parking-lot-go-dingding/model/dingtalk/system"
	"strings"

	"github.com/gin-gonic/gin"
)

func Balance(c *gin.Context) {
	requestStruct := struct {
		CorpId string `json:"corp_id"`
		Page   int    `json:"page"`
		Limit  int    `json:"limit"`
	}{}

	start := (requestStruct.Page - 1) * requestStruct.Limit

	//接收加密串
	if err := c.ShouldBindJSON(&requestStruct); err != nil {
		Fail(c, "json接收失败")
		return
	}

	var err error

	var dingtalkSystemCorpMoneyLogStruct system.DingtalkSystemCorpMoneyLogStruct
	list, err := dingtalkSystemCorpMoneyLogStruct.List(map[string]interface{}{
		"corp_id": requestStruct.CorpId,
	})
	if err != nil {
		Fail(c, "记录查询失败")
	}
	count, err := dingtalkSystemCorpMoneyLogStruct.Count(map[string]interface{}{
		"corp_id": requestStruct.CorpId,
	})
	if err != nil {
		Fail(c, "总数查询失败")
	}

	returnData := make([]map[string]interface{}, 0)

	for _, v := range list {
		operation := ""
		switch v.OperationType {
		case 1:
			operation = "新增会员"
		case 2:
			operation = "修改会员余额"
		case 3:
			operation = "删除会员"
		}

		symbol := ""
		switch v.Type {
		case 1:
			symbol = "+"
		case 2:
			symbol = "-"
		}

		returnData = append(returnData, map[string]interface{}{
			"real_name":      v.RealName,
			"mobile":         v.Mobile,
			"cars":           strings.Split(v.Cars, ","),
			"operation_type": v.OperationType,
			"type":           v.Type,
			"money":          fmt.Sprintf("%.2f", v.Money),
			"desc":           v.Desc,
			"created_at":     v.CreatedAt.Format("2006-01-02 15:04"),
			"operation":      operation,
			"symbol":         symbol,
		})
	}

	Success(c,
		map[string]interface{}{
			"list":         returnData,
			"current_page": start,
			"last_page":    math.Ceil(float64(count) / float64(requestStruct.Limit)),
		})
}
